<template>
  <div class="SalesRegister">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="SalesRegister-form">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="订单编号" prop="orderNo">
            <div class="SalesRegister-form-orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入订单编号" class="SalesRegister-form-orderNo-input"/>
              <el-button type="primary" class="SalesRegister-form-orderNo-btn" @click="generateOrderNo">随机生成
              </el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户" prop="customerId">
            <el-select v-model="form.customerId" placeholder="请选择客户" filterable clearable
                       class="SalesRegister-form-input">
              <el-option v-for="c in customersRef" :key="c.id" :label="c.name" :value="c.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.note" type="textarea" :rows="4" placeholder="可填写备注"
                      class="SalesRegister-form-input"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="SalesRegister-table">
      <div class="SalesRegister-table-toolbar">
        <el-button type="primary" @click="openSelectProduct">添加商品</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
      <el-table :data="items" class="SalesRegister-table-main" border stripe>
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <el-table-column prop="code" label="商品编码" min-width="120" align="center"/>
        <el-table-column prop="name" label="商品名称" min-width="160" align="center"/>
        <el-table-column prop="unit" label="单位" width="100" align="center"/>
        <el-table-column prop="quantity" label="数量" width="120" align="center"/>
        <el-table-column prop="unitPrice" label="单价(¥)" width="120" align="center">
          <template #default="{row}">{{ formatMoney(row.unitPrice) }}</template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="小计(¥)" width="140" align="center">
          <template #default="{row}">{{ formatMoney(row.totalPrice) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{row,$index}">
            <el-button size="small" type="primary" @click="editItem(row,$index)">编辑</el-button>
            <el-button size="small" type="danger" @click="removeItem($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="SalesRegister-table-summary">
        <div class="SalesRegister-table-summary-row">
          <div class="SalesRegister-table-summary-label">合计金额：</div>
          <div class="SalesRegister-table-summary-value">¥ {{ formatMoney(totalAmount) }}</div>
        </div>
      </div>
    </div>

    <div class="SalesRegister-actions">
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </div>

    <ProductSelectDialog v-model:visible="selectDialogVisible" @selected="handleProductSelected"/>
    <ProductItemDialog v-model:visible="itemDialogVisible" :product-id="currentProductId" :product="currentProduct"
                       :initial="currentItemInitial" mode="sale" @confirm="handleItemConfirm"/>
    <SalesSaveConfirmDialog v-model:visible="saveConfirmVisible" :info="saveInfo" :items="items"
                            @confirm="handleSaveConfirm"/>
  </div>
</template>
<script setup>
import {ref, reactive, computed, watch, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import ProductSelectDialog from '../../../../components/ProductSelectDialog.vue'
import ProductItemDialog from '../.././components/ProductItemDialog.vue'
import SalesSaveConfirmDialog from './SalesSaveConfirmDialog.vue'
import {listCustomers} from "../../../../api/customerApi.js";
import {addSalesOrder} from "../../../../api/salesOrderApi.js";

// 本组件内演示客户数据（后续可替换为API）
const customersRef = ref([])

// 组件状态
const formRef = ref()
// 销售单基本信息
const form = reactive({orderNo: '', customerId: null, orderDate: '', note: '', items: [], totalAmount: 0})
// 表单校验规则
const rules = reactive({
  orderNo: [{required: true, message: '请输入订单编号', trigger: 'blur'}],
  customerId: [{required: true, message: '请选择客户', trigger: 'change'}]
})
// 销售商品列表
const items = ref([])
// 同步 items 到 form.items
watch(items, val => {
  form.items = val.map(i => ({...i}))
}, {deep: true, immediate: true})
// 计算总价
const totalAmount = computed(() => items.value.reduce((a, c) => a + Number(c.totalPrice || 0), 0))
// 同步 totalAmount 到 form.totalAmount
watch(totalAmount, v => form.totalAmount = Number(v || 0), {immediate: true})

// 弹窗状态及相关数据
const selectDialogVisible = ref(false)
const itemDialogVisible = ref(false)
const saveConfirmVisible = ref(false)
const currentProduct = ref(null)
const currentProductId = ref(null)
const currentEditIndex = ref(-1)
const currentItemInitial = ref(null)

// 生成随机订单编号
const generateOrderNo = () => {
  const code = Math.floor(Math.random() * 100000000).toString().padStart(8, '0');
  form.orderNo = code;
  ElMessage.success('已生成: ' + code)
}

// 设置系统时间（只读显示）
const formatDate = (d) => {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`
}

// 事件处理
const openSelectProduct = () => {
  selectDialogVisible.value = true
}

// 选择商品后打开编辑弹窗
const handleProductSelected = (p) => {
  selectDialogVisible.value = false;
  if (!p) return;
  currentProduct.value = null;
  currentProductId.value = p.id;
  currentItemInitial.value = null;
  currentEditIndex.value = -1;
  itemDialogVisible.value = true
}

// 商品编辑弹窗确认
const handleItemConfirm = (payload) => {
  if (currentEditIndex.value >= 0) {
    items.value.splice(currentEditIndex.value, 1, payload)
  } else {
    items.value.push(payload)
  }
  itemDialogVisible.value = false
}

// 编辑或删除商品
const editItem = (row, idx) => {
  currentProductId.value = null;
  currentProduct.value = {id: row.productId, code: row.code, name: row.name, unit: row.unit, salePrice: row.unitPrice};
  currentItemInitial.value = {
    quantity: row.quantity,
    unitPrice: row.unitPrice,
    totalPrice: row.totalPrice,
    priceMode: row.priceMode || 'unit'
  };
  currentEditIndex.value = idx;
  itemDialogVisible.value = true
}

// 删除商品
const removeItem = (idx) => items.value.splice(idx, 1)

// 重置表单
const handleReset = () => {
  form.orderNo = '';
  form.customerId = null;
  form.orderDate = formatDate(new Date());
  form.note = '';
  items.value = [];
  form.items = [];
  form.totalAmount = 0
}

// 提交保存
const customerName = computed(() => {
  const c = customersRef.value.find(i => i.id === form.customerId);
  return c ? c.name : ''
})

// 保存信息（仅供确认弹窗显示）
const saveInfo = computed(() => ({
  orderNo: form.orderNo,
  customerId: form.customerId,
  customerName: customerName.value,
  orderDate: form.orderDate,
  note: form.note,
  totalAmount: form.totalAmount
}))

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    saveConfirmVisible.value = true
  } catch (e) {
  }
}

// 确认保存（调用销售保存接口）
const handleSaveConfirm = async () => {
  saveConfirmVisible.value = false;
  await addSalesOrder(form).then((res) => {
    if (res) {
      ElMessage.success('销售单已保存')
      handleReset()
    }
  })
}

// 金额格式化
const formatMoney = v => Number(v || 0).toFixed(2)

// 加载客户列表
const loadCustomers = async () => {
  await listCustomers({condition: {}}).then((res) => {
    customersRef.value = res.list || []
  }).catch((e) => {
    console.error('获取客户列表失败:', e)
    customersRef.value = []
  })
}

// 初始化订单日期为系统时间
onMounted(() => {
  form.orderDate = formatDate(new Date())
  loadCustomers()
})
</script>
<style scoped lang="scss">
.SalesRegister {
  &-form {
    padding: 16px 0;

    &-orderNo {
      display: flex;
      align-items: center;
      gap: 8px;

      &-input {
        flex: 1;
      }

      &-btn {
        flex: 0 0 auto;
        white-space: nowrap;
      }
    }

    &-input {
      width: 100%;
    }
  }

  &-table {
    padding: 16px 0;
    border-top: 1px solid #eee;

    &-toolbar {
      display: flex;
      gap: 8px;
      padding: 16px 0;
      border-bottom: 1px solid #eee;
    }

    &-main {
      width: 100%;
    }

    &-summary {
      display: flex;
      justify-content: flex-end;
      padding: 16px 0;

      &-row {
        display: flex;
        gap: 8px;
        align-items: center;
      }

      &-label {
        font-size: 14px;
        color: #606266;
      }

      &-value {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  &-actions {
    display: flex;
    justify-content: flex-end;
    padding: 16px 0;
    border-top: 1px solid #eee;
  }
}
</style>
